using System;
using System.Diagnostics;
using Microsoft.Office.Interop.Outlook;
using MSOffice = Microsoft.Office.Core;

namespace Office.Utility.Toolbar
{
    /// <summary>
    /// Simple adapter class for the explorer and inspector window objects. Provides a generic mechanism to access
    /// the common properties and methods of both window object types. Also adapts the event signatures to include a 
    /// reference to the object firing the event
    /// </summary>
    internal sealed class WindowAdapter
    {
        readonly object _window;

        public event EventHandler Activate;
        public event EventHandler Close;
        public event EventHandler SelectionChange;

        // ReSharper disable SuggestBaseTypeForParameter
        public WindowAdapter(Explorer explorer)
        {
            _window = explorer;

            var events = (ExplorerEvents_10_Event)explorer;
            events.Activate += (() =>{ if (Activate != null) Activate(this, null);});
            events.Close += (() => { if (Close != null) Close(this, null); });
            events.SelectionChange += (() => { if (SelectionChange != null) SelectionChange(this, null); });
            events.FolderSwitch += (() => { if (SelectionChange != null) SelectionChange(this, null); });
        }

        public WindowAdapter(Inspector inspector)
        {
            _window = inspector;

            var events = (InspectorEvents_10_Event)inspector;
            events.Activate += (() => { if (Activate != null) Activate(this, null); });
            events.Close += (() => { if (Close != null) Close(this, null); });
        }
        // ReSharper restore SuggestBaseTypeForParameter

        [DebuggerHidden]
        [DebuggerNonUserCode]
        public MSOffice.CommandBars CommandBars
        {
            get
            {
                //The CommandBars collection is not available on newly constructed explorer windows. 
                //In this scenario, accessing the CommandBars collection throws an exception. 
                //Here, we trap the exception and return null instead.
                try
                {
                    return (MSOffice.CommandBars)_window.GetType().InvokeMember(
                        "CommandBars",
                        System.Reflection.BindingFlags.GetProperty,
                        null, _window, null);
                }
                catch (System.Reflection.TargetInvocationException)
                {
                    return null;
                }
            }
        }

        public Explorer Explorer
        {
            get { return _window as Explorer; }
        }

        public Inspector Inspector
        {
            get { return _window as Inspector; }
        }
    }


}
